const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const logger = require('koa-logger')
var cors = require('koa2-cors');
const { wssrouter } = require("./routes/wss")
const { koaBody } = require("koa-body");
const path = require("path");
const response = require("./utils/response")
const jwt = require("jsonwebtoken");
const secret = 'tuisa';
const socks = require("./routes/socks")
require("./utils/db")
app.use(async (ctx, next) => {

  try {
    await next();
  } catch (err) {
    console.error(err); // Log the error
    // // Set the status code and response body
    ctx.status = err.status || 500; // Default to 500 if no status set
    ctx.body = {
      message: err.message || 'Internal Server Error',
      code: ctx.status,
    };
  }
})


// error handler

// logger
function createKoaBodyWithTokenCheck(ctx, next) {
  return koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 100 * 1024 * 1024,
      uploadDir: path.join(__dirname, `public/covers`),
      keepExtensions: true,
      onFileBegin: async (name, file) => {
        const token = ctx.request.headers['authorization'];
        if (!token) {
          return response.error(ctx, { message: 'Missing token. 文件上传不允许.' });
        }
        let authHeader = ctx.request.header.authorization || ctx.headers.authorization
        // await verify(ctx, next, true)
        try {
          jwt.verify(authHeader.split(' ')[1], secret);
        } catch (error) {
          return response.error(ctx, { message: 'Invalid token. 文件上传不允许.' });
        }
        if (name === 'cover') {
          const dir = path.join(__dirname, `public/covers`);
          file.filepath = `${dir}/${file.newFilename}`;
        } else if (name === 'attach') {
          const dir = path.join(__dirname, `public/attach`);
          file.filepath = `${dir}/${file.newFilename}`;
        } else {
          return response.error(ctx, { message: '文件上传参数错误' });
        }
      },
      onError: (err) => {
        console.error('File upload error:', err);
      },
    },
  });
}
// middlewares
app
  .use(cors())
  .use(json())
  .use(logger())
  .use(require('koa-static')(__dirname + '/public'))
  .use(require('koa-static')(__dirname + '/views'))
  .use(require('koa-static')(__dirname + '/views/jbb'))
  .use(require('koa-static')(__dirname + '/views/bhm'))
  .use(require('koa-static')(__dirname + '/public/covers'))
  .use(require('koa-static')(__dirname + '/public/avatars'))
  .use(require('koa-static')(__dirname + '/public/attach'))
  .use(views(__dirname + '/views', {
    extension: 'html',
    map: { html: 'ejs' }
  }))
  .use(async (ctx, next) => {
    const koaBodyMiddleware = createKoaBodyWithTokenCheck(ctx, next);
    await koaBodyMiddleware(ctx, next);
  }).
  use(socks.routes(), socks.allowedMethods())
  ;
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    // Set the status code and response body
    ctx.status = err.status || 500; // Default to 500 if no status set
    ctx.body = {
      message: err.message || 'Internal Server Error',
      code: ctx.status,
    };
  }
})
module.exports = app
